package com.yjz.middleware.zookeeper;

import lombok.extern.slf4j.Slf4j;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.junit.Test;

import java.io.IOException;

/**
 * @author :yuanJinZhong
 * @description:zookeeper学习
 * @date :2018/7/20-17:31
 */
@Slf4j
public class ZookeeperStudy {

  @Test
  public void testzk() throws IOException {
    ZkClient zkClient = new ZkClient("localhost:2181", 1000);
    //获取指定路径的子节点个数
    log.info("获取指定路径的子节点个数:" + zkClient.countChildren("/"));

    //如果节点存在则删除该节点
//		if (zkClient.exists("/dubbo")) {
//			log.info("如果节点存在则删除该节点:");
//			zkClient.delete("/dubbo");
//		}
    //创建永久的节点
//		String nodeName = zkClient.create("/yuan", "{\"name\":\"admin\"}", CreateMode.PERSISTENT);
//		log.info("创建的节点名字 {}",nodeName);


    log.info("读取节点的信息 {}", zkClient.readData("/yuan").toString());

    //订阅dubbo数据的变化
    zkClient.subscribeDataChanges("/yuan", new IZkDataListener() {
      @Override
      public void handleDataChange(String dataPath, Object data) throws Exception {
        System.out.println(dataPath + "节点数据发生变化。。。");
      }

      @Override
      public void handleDataDeleted(String dataPath) throws Exception {
        System.out.println(dataPath + "节点数据被删除....");
      }
    });
//		//订阅dubbo子节点的变化
    zkClient.subscribeChildChanges("/yuan", (parentPath, currentChilds) -> System.out.println("dubbo节点发生变化"));
//
//		//更新dubbo节点的数据
    zkClient.writeData("/yuan", "sadsadsadsadsadasd");
    System.in.read();
  }

  /**
   * curator客户端操作zookeeper, address :47.98.237.214 2181
   * https://blog.csdn.net/wo541075754/article/details/69138878?utm_source=gold_browser_extension
   */
  @Test
  public void zkWithcurator() throws Exception {
    RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
    CuratorFramework client = CuratorFrameworkFactory.newClient("47.98.237.214", retryPolicy);
    client.start();
    client.setData().forPath("/lock", "我是更11".getBytes());
    client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/ephemeral", "这是一个临时有序节点".getBytes());

  }

}
